import React, { Component } from 'react';
import { Card, Form, Input, Button } from 'antd';
import qs from 'qs';
import { postManage, detailManage } from 'Services/publicServer.js';

const FormItem = Form.Item;

@Form.create()
export default class siteDetails extends Component {
  constructor(props) {
    super(props);
    window.scope = this;
  }

  state = {
    list: {},
  };

  componentDidMount() {
    this.getSiteData();
  }

  getSiteData = async () => {
    const { type, id } = this;
    if (type === 'add') return false;
    const { setFieldsValue } = this.props.form;
    const res = await detailManage({ userId: id });
    this.setState({ list: res.data });
    const { userName, password, userId } = res.data;
    if (type === 'edit') setFieldsValue({ userName, password, userId });
  };

  id = qs.parse(this.props.location.search.substr(1)).id;

  type = this.props.match.params.type;

  handleSubmit = e => {
    e.preventDefault();
    const { validateFields } = this.props.form;
    validateFields((err, value) => {
      if (err) return false;
      const data = {
        ...value,
      };
      if (this.type === 'edit') {
        data.userId = this.id;
        data.flag = '1';
      } else {
        data.flag = '0';
      }
      postManage(data).then(() => {
        this.props.history.push('/administrator/manage');
      });
    });
  };

  render() {
    const { type } = this.props.match.params;
    const isAdd = type === 'add';
    const title = isAdd ? '新增管理员' : '编辑管理员';
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: {
        span: 8,
      },
      wrapperCol: {
        span: 16,
      },
    };
    const { list } = this.state;

    return (
      <div>
        <Card title={title}>
          <Form onSubmit={this.handleSubmit} style={{ maxWidth: '500px' }}>
            <FormItem label="用户名" {...formItemLayout}>
              {getFieldDecorator('userName', {
                rules: [{ required: true }],
              })(<Input placeholder="请输入用户名" />)}
            </FormItem>

            <FormItem label="用户ID" {...formItemLayout}>
              {isAdd ? (
                getFieldDecorator('userId', {
                  rules: [{ required: true }],
                })(<Input placeholder="请输入用户ID" />)
              ) : (
                <span>{list.userId}</span>
              )}
            </FormItem>

            <FormItem label="密码" {...formItemLayout}>
              {getFieldDecorator('password', {
                rules: [{ required: true }],
              })(<Input placeholder="请输入密码" />)}
            </FormItem>

            <FormItem wrapperCol={{ offset: 8 }}>
              <Button type="primary" htmlType="submit">
                提交
              </Button>
            </FormItem>
          </Form>
        </Card>
      </div>
    );
  }
}
